<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>极简论坛</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
        }

        body {
            background: #f8f9fa;
            color: #212529;
        }

        .container {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }

        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 40px;
            position: relative;
        }

        .user-info-container {
            display: flex;
            align-items: center;
            gap: 15px;
            flex-direction: row-reverse;
            /* 将按钮放在右边 */

        }

        .user-info {
            display: flex;
            align-items: center;
            flex-direction: row;
            /* 头像和菜单水平排列 */
            padding: 0 10px 0 0;
        }

        #newPost {
            margin-left: auto;
            /* 将按钮推到最右侧 */
        }

        .user-avatar {
            width: 40px;
            height: 40px;
            border-radius: 10%;
            object-fit: cover;
            border: 2px solid #fff;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .user-menu {
            position: absolute;
            right: 0;
            top: 50px;
            background: white;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            border-radius: 8px;
            padding: 10px 0;
            width: 120px;
            display: none;
            z-index: 1000;
        }

        .menu-item {
            padding: 8px 16px;
            transition: background 0.2s;
            cursor: pointer;
        }

        .menu-item:hover {
            background: #f8f9fa;
        }

        .post {
            background: white;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        }

        .post-header {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 15px;
        }

        .post-avatar {
            width: 32px;
            height: 32px;
            border-radius: 10%;
            object-fit: cover;
        }

        .modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.8);
            display: none;
            align-items: center;
            justify-content: center;
            z-index: 1000;
        }

        .modal-content {
            background: white;
            padding: 30px;
            border-radius: 8px;
            width: 90%;
            max-width: 500px;
        }

        input,
        textarea {
            width: 100%;
            padding: 12px 16px;
            margin: 8px 0;
            border: 2px solid #e0e0e0;
            border-radius: 6px;
            font-size: 14px;
            line-height: 1.5;
            color: #333;
            background-color: #f8f9fa;
            transition: all 0.3s ease;
            box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.08);
            -webkit-appearance: none;
            -moz-appearance: none;
            appearance: none;
        }

        /* 悬停状态 */
        input:hover,
        textarea:hover {
            border-color: #90caf9;
            box-shadow: 0 2px 6px rgba(144, 202, 249, 0.2);
        }

        /* 聚焦状态 */
        input:focus,
        textarea:focus {
            outline: none;
            border-color: #42a5f5;
            box-shadow: 0 3px 8px rgba(66, 165, 245, 0.3),
                inset 0 1px 2px rgba(0, 0, 0, 0.05);
            background-color: #fff;
        }

        /* 占位符样式 */
        ::placeholder {
            color: #9e9e9e;
            opacity: 1;
            font-style: italic;
        }

        /* 禁用状态 */
        input:disabled,
        textarea:disabled {
            background-color: #f5f5f5;
            opacity: 0.7;
            cursor: not-allowed;
        }

        /* 错误状态 */
        .input-error {
            border-color: #ef5350 !important;
            background-color: #ffebee;
            animation: shake 0.4s ease;
        }

        @keyframes shake {

            0%,
            100% {
                transform: translateX(0);
            }

            20%,
            60% {
                transform: translateX(-4px);
            }

            40%,
            80% {
                transform: translateX(4px);
            }
        }

        button {
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            background: #007bff;
            color: white;
            transition: opacity 0.2s;
        }

        button:hover {
            opacity: 0.9;
        }

        .toolbar {
            display: flex;
            gap: 10px;
            margin-top: 15px;
        }

        .time {
            color: #6c757d;
            font-size: 0.9em;
            margin: 10px 0;
        }

        .message-toast {
            position: fixed;
            top: 20px;
            left: 50%;
            transform: translateX(-50%);
            background: rgba(0, 0, 0, 0.9);
            color: white;
            padding: 12px 24px;
            border-radius: 4px;
            display: none;
            z-index: 2000;
            animation: fadeInOut 3s forwards;
        }

        @keyframes fadeInOut {
            0% {
                opacity: 0;
                top: 0;
            }

            10% {
                opacity: 1;
                top: 20px;
            }

            90% {
                opacity: 1;
                top: 20px;
            }

            100% {
                opacity: 0;
                top: 0;
            }
        }

        .preview-avatar {
            width: 100px;
            height: 100px;
            border-radius: 10%;
            object-fit: cover;
            margin: 10px 0;
        }

        /* 自定义确认弹窗样式 */
        .confirm-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.6);
            display: none;
            align-items: center;
            justify-content: center;
            z-index: 1000;
        }

        .confirm-content {
            background: white;
            padding: 25px;
            border-radius: 8px;
            max-width: 400px;
            text-align: center;
            animation: modalSlideIn 0.3s ease;
        }

        @keyframes modalSlideIn {
            from {
                transform: translateY(-50px);
                opacity: 0;
            }

            to {
                transform: translateY(0);
                opacity: 1;
            }
        }

        .confirm-buttons {
            margin-top: 20px;
            display: flex;
            gap: 15px;
            justify-content: center;
        }

        .confirm-ok {
            background: #ff4444;
            color: white;
        }

        .confirm-cancel {
            background: #f0f0f0;
            color: #666;
        }

        .username-display {
            font-weight: 500;
            color: #2c3e50;
            transition: color 0.2s;
        }

        .user-info:hover .username-display {
            color: #3498db;
        }

        .menu-item.username-change {
            color: #3498db;
            border-bottom: 1px solid #eee;
            padding-bottom: 8px;
            margin-bottom: 8px;
        }

        #usernameModal input {
            font-size: 16px;
            padding: 12px;
            margin: 20px 0;
        }
    </style>
</head>

<body>
    <div class="message-toast" id="messageToast"></div>

    <div class="container">
        <div class="header">
            <h1>极简论坛</h1>
            <div id="userInfo" class="user-info">
                <!-- 头像 -->
            </div>
        </div>
        <div id="posts"></div>
    </div>

    <!-- 登录弹窗 -->
    <div class="modal" id="loginModal">
        <div class="modal-content">
            <h2>登录 / 注册</h2>
            <input type="text" id="username" placeholder="用户名">
            <input type="password" id="password" placeholder="密码">
            <div class="toolbar">
                <button onclick="handleLogin()">登录</button>
                <button onclick="handleRegister()">注册</button>
            </div>
        </div>
    </div>

    <!-- 发帖弹窗 -->
    <div class="modal" id="postModal">
        <div class="modal-content">
            <h2>发布新帖</h2>
            <input type="text" id="postTitle" placeholder="标题">
            <textarea id="postContent" rows="6" placeholder="内容"></textarea>
            <button onclick="createPost()">发布</button>
        </div>
    </div>

    <!-- 头像修改弹窗 -->
    <div class="modal" id="avatarModal">
        <div class="modal-content">
            <h2>更改头像</h2>
            <input type="file" id="avatarInput" accept="image/*">
            <div class="preview" id="avatarPreview"></div>
            <button onclick="uploadAvatar()">保存</button>
        </div>
    </div>




    <!-- 自定义确认弹窗 -->
    <div class="confirm-modal" id="deleteConfirmModal">
        <div class="confirm-content">
            <h3>确认删除</h3>
            <p>确定要永久删除这篇帖子吗？</p>
            <div class="confirm-buttons">
                <button class="confirm-cancel">取消</button>
                <button class="confirm-ok">确认删除</button>
            </div>
        </div>
    </div>
    <!-- 用户名修改弹窗 -->
    <div class="modal" id="usernameModal">
        <div class="modal-content">
            <h2>修改用户名</h2>
            <input type="text" id="newUsername" placeholder="新用户名">
            <div class="modal-buttons">
                <button onclick="updateUsername()">确认修改</button>
                <button onclick="hideUsernameModal()">取消</button>
            </div>
        </div>
    </div>

    <script>
        const defaultAvatar = '';

        // 消息提示
        function showMessage(text, type = 'info') {
            const toast = document.getElementById('messageToast');
            toast.textContent = text;
            toast.style.display = 'block';
            setTimeout(() => toast.style.display = 'none', 3000);
        }

        function showAvatarModal() {
            hideModals();
            document.getElementById('avatarModal').style.display = 'flex';
        }

        // 用户信息显示
        function updateUserInfo() {
            const userInfoContainer = document.getElementById('userInfo');
            if (sessionStorage.getItem('userId')) {
                userInfoContainer.innerHTML = `
                <div class="user-info" onclick="toggleUserMenu()">
                    <span class="username-display">${sessionStorage.getItem('user')}</span>
                    <img class="user-avatar" src="${sessionStorage.getItem('avatar') || defaultAvatar}">
                    <div class="user-menu" id="userMenu">
                        <div class="menu-item username-change" onclick="showUsernameModal()">修改用户名</div>
                        <div class="menu-item" onclick="showAvatarModal()">更改头像</div>
                        <div class="menu-item" onclick="logout()">退出登录</div>
                    </div>
                </div>
                <button id="newPost">发布新帖</button>
                `;

                // 调整事件绑定方式
                document.getElementById('newPost').addEventListener('click', () => {
                    document.getElementById('postModal').style.display = 'flex';
                });
            } else {
                userInfoContainer.innerHTML = '';
            }
        }

        // 更新用户名逻辑
        async function updateUsername() {
            const newUsername = document.getElementById('newUsername').value.trim();
            const oldUsername = sessionStorage.getItem('user');

            if (!newUsername) {
                showMessage('用户名不能为空', 'error');
                return;
            }
            const users = await (await fetch('/tables/users/items')).json();
            if (users.some(u => u.username === newUsername)) {
                showMessage('用户名已存在', 'error');
                return;
            }

            try {
                // 更新数据库
                const response = await fetch(`/tables/users/items/${sessionStorage.getItem('userId')}`, {
                    method: 'PUT',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        username: newUsername
                    })
                });

                if (response.ok) {
                    // 更新本地存储
                    sessionStorage.setItem('user', newUsername);

                    // 更新页面显示
                    document.querySelector('.username-display').textContent = newUsername;

                    // 更新历史帖子
                    updatePostsUsername(oldUsername, newUsername);

                    showMessage('用户名修改成功');
                    hideUsernameModal();
                    hideModals()


                }
            } catch (error) {
                showMessage('修改失败，请重试', 'error');
            }
        }

        async function updatePostsUsername(oldName, newName) {
            console.log('更新所有帖子中的用户名');

            try {
                // 获取posts表的所有数据项
                const response = await fetch('/tables/posts/items');
                const posts = await response.json();

                // 过滤出所有该用户发的帖子
                const userPosts = posts.filter(post => post.user === oldName);

                // 逐个更新帖子
                for (const post of userPosts) {
                    await fetch(`/tables/posts/items/${post.id}`, {
                        method: 'PUT',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({
                            user: newName  // 直接更新user字段
                        })
                    });
                }

                // console.log('用户名更新完成');
                // showMessage('用户名更新完成');

                updateUserInfo();
                loadPosts()

            } catch (error) {
                console.error('更新帖子用户名失败:', error);
                throw error;  // 抛出错误让外层catch捕获
            }
        }


        // 显示用户名修改弹窗
        function showUsernameModal() {
            const modal = document.getElementById('usernameModal');
            document.getElementById('newUsername').value = sessionStorage.getItem('user');
            modal.style.display = 'flex';
            toggleUserMenu(); // 关闭用户菜单
        }

        // 隐藏用户名修改弹窗
        function hideUsernameModal() {
            document.getElementById('usernameModal').style.display = 'none';
        }

        // 用户菜单切换
        function toggleUserMenu() {
            const menu = document.getElementById('userMenu');
            menu.style.display = menu.style.display === 'block' ? 'none' : 'block';
        }

        // 用户注册
        async function handleRegister() {
            const username = document.getElementById('username').value.trim();
            const password = document.getElementById('password').value.trim();

            if (!username || !password) {
                showMessage('用户名和密码不能为空', 'error');
                return;
            }

            try {
                const users = await (await fetch('/tables/users/items')).json();
                if (users.some(u => u.username === username)) {
                    showMessage('用户名已存在', 'error');
                    return;
                }

                await fetch('/tables/users/items', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        data: {
                            username,
                            password,
                            avatar: defaultAvatar
                        }
                    })
                });

                // const newUser = await response.json();
                // // //打印 newUser
                // console.log(response);
                // console.log(newUser);
                // sessionStorage.setItem('userId', newUser.id);
                // sessionStorage.setItem('user', username);
                // sessionStorage.setItem('avatar', defaultAvatar);
                // updateUserInfo();
                showMessage('注册成功');
                // hideModals();
                // loadPosts();

                setTimeout(() => {
                    handleLogin()
                }, 1000);


            } catch (error) {
                showMessage('注册失败', 'error');
                Create_a_table_structure()
            }
        }

        // 用户登录
        async function handleLogin() {
            const username = document.getElementById('username').value.trim();
            const password = document.getElementById('password').value.trim();

            try {
                const users = await (await fetch('/tables/users/items')).json();
                const user = users.find(u => u.username === username && u.password === password);
                //打印 user
                // console.log(user);

                if (user) {
                    sessionStorage.setItem('userId', user.id);
                    sessionStorage.setItem('user', username);
                    sessionStorage.setItem('avatar', user.avatar || defaultAvatar);
                    updateUserInfo();
                    showMessage('登录成功');
                    hideModals();
                    loadPosts();
                } else {
                    showMessage('用户名或密码错误', 'error');
                }
            } catch (error) {
                showMessage('登录失败', 'error');
            }
        }

        // 头像上传
        document.getElementById('avatarInput').addEventListener('change', function (e) {
            const file = e.target.files[0];
            if (file && file.type.startsWith('image/')) {
                const reader = new FileReader();
                reader.onload = (event) => {
                    document.getElementById('avatarPreview').innerHTML = `
                    <img src="${event.target.result}" class="preview-avatar">
                `;
                };
                reader.readAsDataURL(file);
            }
        });

        async function uploadAvatar() {
            const file = document.getElementById('avatarInput').files[0];
            if (!file) return;

            // 添加文件大小限制（200KB = 200 * 1024 bytes）
            const MAX_SIZE = 200 * 1024;
            if (file.size > MAX_SIZE) {
                showMessage('文件大小不能超过200KB', 'error');
                return;
            }

            // 定义允许的文件类型白名单
            const allowedTypes = [
                'image/jpeg',      // JPEG文件
                'image/png',       // PNG文件
                'image/gif',       // GIF文件
                'image/webp',      // WebP格式
                'image/svg+xml'    // SVG矢量图
            ];

            // 严格类型验证
            if (!allowedTypes.includes(file.type)) {
                showMessage('仅支持 JPG/PNG/GIF/WEBP/SVG 格式', 'error');
                return;
            }

            const reader = new FileReader();
            reader.readAsDataURL(file);

            reader.onload = async () => {
                try {
                    // 1. 更新用户表
                    const userId = sessionStorage.getItem('userId');
                    const res = await fetch(`/tables/users/items/${userId}`, {
                        method: 'PUT',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ avatar: reader.result })
                    });

                    if (res.ok) {
                        // 2. 更新本地存储
                        sessionStorage.setItem('avatar', reader.result);

                        // 3. 更新所有历史帖子
                        await updateAllPostAvatars(userId, reader.result);

                        // 4. 刷新界面显示
                        updateUserInfo();
                        loadPosts();
                        showMessage('头像更新成功');
                        hideModals()
                    }



                    // if (res.ok) {
                    //     // 更新本地缓存和界面
                    //     const username = sessionStorage.getItem('user');
                    //     userCache[username] = {
                    //         ...userCache[username],
                    //         avatar: reader.result
                    //     };

                    //     sessionStorage.setItem('avatar', reader.result);
                    //     updateUserInfo();
                    //    loadPosts();  // 重要：重新加载帖子更新所有头像
                    //     showMessage('头像更新成功');
                    //     hideModals()
                    // }


                } catch (error) {
                    showMessage('头像更新失败', 'error');
                }
            };
        }

        // 新增核心更新函数
        async function updateAllPostAvatars(userId, newAvatar) {

            try {
                // 获取用户名
                users = sessionStorage.getItem('user')
                // 打印 用户名
                // console.log(users);


                // 获取posts表的所有数据项
                const response = await fetch('/tables/posts/items');
                const posts = await response.json();

                // 过滤出所有该用户发的帖子
                const userPosts = posts.filter(post => post.user === users);

                // 逐个更新帖子
                for (const post of userPosts) {
                    await fetch(`/tables/posts/items/${post.id}`, {
                        method: 'PUT',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({
                            avatar: newAvatar
                        })
                    });
                }

                updateUserInfo();
                loadPosts()
            

            } catch (error) {
                console.error('帖子头像更新失败:', error);
                throw error;
            }
        }


        async function loadPosts() {
            try {
                // 获取所有帖子
                const postsRes = await fetch('/tables/posts/items');
                const posts = await postsRes.json();
                const idSorted = posts.sort((a, b) => b.id - a.id); // 按id降序排序

                // 渲染帖子
                const html = posts.map(post => `
                    <div class="post">
                        <div class="post-header">
                            <img src="${post.avatar}" 
                                class="post-avatar"
                                onerror="this.src='${defaultAvatar}'">
                            <div>
                                <div>${post.user}</div>
                                <div class="time">${post.time}</div>
                            </div>
                        </div>
                        <h3>${post.title}</h3>
                        <p>${post.content}</p>
                        <div class="toolbar">
                            <button onclick="copyPost('${post.title}', '${post.content}')">复制</button>
                            ${post.user === sessionStorage.getItem('user') ?
                        `<button onclick="deletePost(${post.id})">删除</button>` : ''}
                        </div>
                    </div>
                `).join('');

                document.getElementById('posts').innerHTML = html;



                // 收集所有用户名
                // const usernames = [...new Set(posts.map(p => p.user))];

                // // 批量获取用户信息（假设API支持username过滤）
                // const usersRes = await fetch(`/tables/users/items?filter=username IN (${usernames.map(u => `'${u}'`).join(',')})`);
                // const users = await usersRes.json();

                // // 更新用户缓存
                // users.forEach(u => {
                //     userCache[u.username] = {
                //         avatar: u.avatar || defaultAvatar
                //     };
                // });

                // 渲染帖子（使用缓存数据）
                // const html = posts.map(post => `
                //     <div class="post">
                //         <div class="post-header">
                //             <img src="${userCache[post.user]?.avatar}" 
                //                 class="post-avatar"
                //                 onerror="this.src='${defaultAvatar}'">
                //             <div>
                //                 <div>${post.user}</div>
                //                 <div class="time">${post.time}</div>
                //             </div>
                //         </div>
                //         <h3>${post.title}</h3>
                //         <p>${post.content}</p>
                //         <div class="toolbar">
                //             <button onclick="copyPost('${post.title}', '${post.content}')">复制</button>
                //             ${post.user === sessionStorage.getItem('user') ?
                //         `<button onclick="deletePost(${post.id})">删除</button>` : ''}
                //         </div>
                //     </div>
                // `).join('');

                // document.getElementById('posts').innerHTML = html;
            } catch (error) {
                showMessage('加载失败', 'error');
            }
        }

        async function createPost() {
            const title = document.getElementById('postTitle').value.trim();
            const content = document.getElementById('postContent').value.trim();

            if (!title || !content) {
                showMessage('标题和内容不能为空', 'error');
                return;
            }

            try {
                await fetch('/tables/posts/items', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        data: {
                            title,
                            content,
                            user: sessionStorage.getItem('user'),
                            time: new Date().toLocaleString(),
                            avatar: sessionStorage.getItem('avatar')
                        }
                    })
                });
                showMessage('发布成功');
                hideModals();
                loadPosts();
            } catch (error) {
                showMessage('发布失败', 'error');
            }
        }




        let currentDeleteId = null;

        async function deletePost(id) {
            currentDeleteId = id;
            showDeleteConfirm();
        }

        function showDeleteConfirm() {
            const modal = document.getElementById('deleteConfirmModal');
            modal.style.display = 'flex';

            // 绑定事件
            modal.querySelector('.confirm-ok').onclick = async () => {
                try {
                    await fetch(`/tables/posts/items/${currentDeleteId}`, {
                        method: 'DELETE'
                    });
                    showMessage('删除成功');
                    loadPosts();
                    hideDeleteConfirm();
                } catch (error) {
                    showMessage('删除失败', 'error');
                    hideDeleteConfirm();
                }
            };

            modal.querySelector('.confirm-cancel').onclick = hideDeleteConfirm;
            modal.onclick = (e) => {
                if (e.target === modal) hideDeleteConfirm();
            };
        }

        function hideDeleteConfirm() {
            document.getElementById('deleteConfirmModal').style.display = 'none';
            currentDeleteId = null;
        }

        // 通用功能
        function logout() {
            sessionStorage.clear();
            window.location.reload();
        }
        // 关闭弹窗
        function hideModals() {
            document.querySelectorAll('.modal').forEach(m => m.style.display = 'none');
        }


        function showModal(id) {
            hideModals();
            document.getElementById(id).style.display = 'flex';
        }

        function copyPost(title, content) {
            navigator.clipboard.writeText(`标题：${title}\n内容：${content}`);
            showMessage('内容已复制');
        }

        async function Create_a_table_structure(){
            // 创建表结构
            try {
                await fetch('/tables', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        table_name: "users",
                        columns: {
                            id: "INT AUTO_INCREMENT PRIMARY KEY",
                            username: "VARCHAR(255)",
                            password: "VARCHAR(255)",
                            avatar: "TEXT"
                        }
                    })
                });

                await fetch('/tables', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        table_name: "posts",
                        columns: {
                            id: "INT AUTO_INCREMENT PRIMARY KEY",
                            title: "VARCHAR(255)",
                            content: "VARCHAR(255)",
                            user: "VARCHAR(255)",
                            time: "VARCHAR(255)",
                            avatar: "TEXT"
                        }
                    })
                });
            } catch (e) { }
        }

        // 初始化
        window.onload = async () => {
            

            // 初始化用户界面
            updateUserInfo();
            if (!sessionStorage.getItem('userId')) {
                showModal('loginModal');
            } else {
                loadPosts();
            }

            // 全局点击关闭菜单
            document.addEventListener('click', (e) => {
                if (!e.target.closest('.user-info')) {
                    const menu = document.getElementById('userMenu');
                    if (menu) menu.style.display = 'none';
                }
            });
        };
    </script>
</body>

</html>


